<template>
  <div class="container">
    <XForm
      :fields="fields"
      :value="defaultValue"
      cancel-text="重置"
      ok-text="保存"
      @submit="submit"
    ></XForm>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { updateUserProfile } from '@/api/user-center';
  import { useUserStore } from '@/store';
  import { getDict } from '@/utils/dict';
  import { Message } from '@arco-design/web-vue';

  const userStore = useUserStore();

  const dict = getDict('sys_user_sex');
  const defaultValue = ref({
    nickName: userStore.nickName,
    phonenumber: userStore.phonenumber,
    email: userStore.email,
    sex: userStore.sex,
  });
  const fields = ref([
    {
      key: 'nickName',
      label: '用户昵称',
      placeholder: '请输入用户昵称',
      tag: 'a-input',
      span: 24,
      decorator: {
        rules: [{ required: true, message: '请输入用户昵称' }],
      },
    },
    {
      key: 'phonenumber',
      label: '手机号码',
      placeholder: '请输入手机号码',
      tag: 'a-input',
      span: 24,
      decorator: {
        rules: [
          { required: true, message: '请输入手机号码' },
          {
            match: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur',
          },
        ],
      },
    },
    {
      key: 'email',
      label: '邮箱',
      placeholder: '请输入邮箱',
      tag: 'a-input',
      span: 24,
      decorator: {
        rules: [{ required: true, message: '请输入邮箱', type: 'email' }],
      },
    },
    {
      key: 'sex',
      label: '性别',
      placeholder: '请选择性别',
      tag: 'a-radio-group',
      span: 24,
      attrs: {
        options: dict.sys_user_sex,
      },
      decorator: {
        rules: [{ required: false, message: '请选择性别' }],
      },
    },
  ]);

  const submit = async (e: any) => {
    const { code, msg } = await updateUserProfile({
      ...userStore,
      ...e,
    });
    if (code !== 200) {
      Message.error(msg);
    } else {
      Message.success('修改成功');
      userStore.info();
    }
  };
</script>

<style scoped lang="less">
  .container {
    width: 800px;
    margin: 0 auto;
  }
</style>
